import datetime
import logging
import random
import string
import time
import json

from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

from goods.models import Product
from login.models import UserModel
from orders import models
from orders.models import Order
from orders.seralizers import OrderSerializer
from utils.alipaysdk import AliPaySDK

logger = logging.getLogger('django')


class Order_Show_View(APIView):
    def get(self, request):
        order_list = Order.objects.all()
        ser = OrderSerializer(instance=order_list, many=True)
        return Response({'status': 200, 'msg': 'success', 'data': ser.data})


class Order_User_View(APIView):
    def get(self, request):
        user_id = request.query_params.get('user_id')
        if not user_id:
            return Response(
                {'status': 400, 'msg': '缺少用户ID'},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            user = UserModel.objects.get(id=user_id)
            order_list = Order.objects.filter(order_user=user)
            ser = OrderSerializer(instance=order_list, many=True)
            return Response({'status': 200, 'msg': 'success', 'data': ser.data})
        except UserModel.DoesNotExist:
            return Response(
                {'status': 404, 'msg': '用户不存在'},
                status=status.HTTP_404_NOT_FOUND
            )


class Order_Add_View(APIView):
    def post(self, request):
        user_id = request.data.get('user_id')
        product_id = request.data.get('product_id')

        if not user_id or not product_id:
            return Response(
                {'status': 400, 'msg': '缺少用户ID或商品ID'},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            user = UserModel.objects.get(id=user_id)

            if Order.objects.filter(order_user=user, order_product_id=product_id).exists():
                return Response(
                    {'status': 400, 'msg': '您已拥有该商品，无法重复购买'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            product = Product.objects.get(id=product_id)

            date_str = datetime.datetime.now().strftime("%Y%m%d")
            random_str = ''.join(random.choices(string.ascii_uppercase + string.digits, k=12))
            order_id = f"DT{date_str}{user.id}{random_str}"

            order = Order.objects.create(
                order_id=order_id,
                order_status="未审核",
                order_price=product.price,
                order_time=datetime.datetime.now(),
                order_user=user,
                order_product_id=product_id
            )

            ser = OrderSerializer(order)
            return Response(
                {'status': 201, 'msg': '订单创建成功', 'data': ser.data},
                status=status.HTTP_201_CREATED
            )

        except UserModel.DoesNotExist:
            return Response(
                {'status': 404, 'msg': '用户不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        except Product.DoesNotExist:
            return Response(
                {'status': 404, 'msg': '商品不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {'status': 500, 'msg': f'服务器错误: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class Order_Pay_View(APIView):
    def post(self, request):
        # 获取请求中的用户ID和订单号
        user_id = request.data.get('user_id')
        order_id = request.data.get('order_id')

        # 如果缺少用户ID或订单号，返回400错误
        if not user_id or not order_id:
            return Response(
                {'status': 400, 'msg': '缺少用户ID或订单号'},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            # 根据用户ID获取用户对象
            user = UserModel.objects.get(id=user_id)
            # 根据订单号和用户对象获取订单对象
            order = Order.objects.get(order_id=order_id, order_user=user)

            # 如果订单状态为"已审核,未支付"，返回400错误
            if order.order_status == "已审核,未支付":
                return Response(
                    {'status': 400, 'msg': '订单已完成支付，无需重复操作'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 模拟支付过程，等待5秒
            time.sleep(5)
            # 将订单状态改为"已生效"
            order.order_status = "已生效"
            # 保存订单对象
            order.save()

            # 序列化订单对象
            ser = OrderSerializer(order)
            # 返回200成功响应，包含订单数据
            return Response(
                {'status': 200, 'msg': '订单支付成功', 'data': ser.data},
                status=status.HTTP_200_OK
            )

        # 如果用户对象不存在，返回404错误
        except UserModel.DoesNotExist:
            return Response(
                {'status': 404, 'msg': '用户不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        # 如果订单对象不存在或不属于该用户，返回404错误
        except Order.DoesNotExist:
            return Response(
                {'status': 404, 'msg': '订单不存在或不属于该用户'},
                status=status.HTTP_404_NOT_FOUND
            )
        # 如果发生其他异常，返回500错误
        except Exception as e:
            return Response(
                {'status': 500, 'msg': f'服务器错误: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class Order_Query_View(APIView):
    def get(self, request):
        # 获取请求中的用户ID和状态参数
        user_id = request.query_params.get('user_id')
        status_param = request.query_params.get('status')

        # 如果没有用户ID，返回400错误
        if not user_id:
            return Response(
                {'status': 400, 'msg': '缺少用户ID'},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            # 根据用户ID获取用户对象
            user = UserModel.objects.get(id=user_id)
            # 如果有状态参数，根据用户和状态参数获取订单对象
            if status_param:
                orders = Order.objects.filter(order_user=user, order_status=status_param)
            # 如果没有状态参数，根据用户获取订单对象
            else:
                orders = Order.objects.filter(order_user=user)

            # 将订单对象序列化
            ser = OrderSerializer(orders, many=True)
            # 返回200成功状态和订单数据
            return Response({'status': 200, 'msg': '查询成功', 'data': ser.data})
        # 如果用户不存在，返回404错误
        except UserModel.DoesNotExist:
            return Response(
                {'status': 404, 'msg': '用户不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        # 如果发生其他异常，返回500错误
        except Exception as e:
            return Response(
                {'status': 500, 'msg': f'服务器错误: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class Order_Detail_View(APIView):
    def get(self, request, pk):
        try:
            order = Order.objects.get(pk=pk)
            ser = OrderSerializer(order)
            return Response({
                'status': 200,
                'msg': 'success',
                'data': ser.data
            })
        except Order.DoesNotExist:
            return Response({
                'status': 404,
                'msg': '订单不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'status': 500,
                'msg': f'服务器错误: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class Pay(APIView):
    def get(self, request):
        try:
            order_id = request.query_params.get("order_id")
            if not order_id:
                return Response(
                    {"status": 400, "msg": "订单ID不能为空"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            order = Order.objects.filter(order_id=order_id).first()
            if not order:
                return Response(
                    {"status": 404, "msg": "订单不存在"},
                    status=status.HTTP_404_NOT_FOUND
                )

            if order.order_status != "已审核,未支付":
                return Response(
                    {"status": 400, "msg": "当前订单状态不允许支付"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            ali = AliPaySDK()
            url = ali.page_pay(
                order.order_id,
                float(order.order_price),
                f"购买商品: {order.order_product.name}"
            )

            return Response({
                "status": 200,
                "msg": "支付链接生成成功",
                "data": {"url": url}
            })
        except Exception as e:
            logger.error(f"支付链接生成失败: {str(e)}")
            return Response(
                {"status": 500, "msg": "支付服务异常"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


@method_decorator(csrf_exempt, name='dispatch')
class PayResult(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request):
        """处理支付宝异步通知"""
        try:
            # 尝试多种方式解析数据
            if request.content_type == 'application/x-www-form-urlencoded':
                data = request.POST.dict()
            else:
                try:
                    data = json.loads(request.body.decode('utf-8'))
                except:
                    data = {}

            if not data:
                logger.error("支付宝回调数据为空")
                return Response("failure", status=400)

            ali = AliPaySDK()

            if not ali.check_sign(data):
                logger.error("支付宝回调签名验证失败")
                return Response("failure", status=400)

            out_trade_no = data.get("out_trade_no")
            order = Order.objects.filter(order_id=out_trade_no).first()
            if not order:
                logger.error(f"订单不存在: {out_trade_no}")
                return Response("failure", status=404)

            total_amount = float(data.get("total_amount", 0))
            if abs(total_amount - float(order.order_price)) > 0.01:
                logger.error(f"金额不匹配: 订单{order.order_price} ≠ 回调{total_amount}")
                return Response("failure", status=400)

            # 修复状态检查逻辑
            if order.order_status == "已审核,未支付":
                order.order_status = "已生效"
                order.save()
                logger.info(f"订单状态更新成功: {out_trade_no} -> 已生效")
            else:
                logger.info(f"订单状态无需更新: {out_trade_no} 当前状态: {order.order_status}")

            return Response("success")
        except Exception as e:
            logger.exception(f"支付回调处理异常: {str(e)}")
            return Response("failure", status=500)

    def get(self, request):
        """处理支付宝同步通知"""
        try:
            data = request.query_params.dict()
            ali = AliPaySDK()

            if not ali.check_sign(data):
                return Response(
                    {"status": 400, "msg": "支付验证失败"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            out_trade_no = data.get("out_trade_no")
            order = Order.objects.filter(order_id=out_trade_no).first()
            if not order:
                return Response(
                    {"status": 404, "msg": "订单不存在"},
                    status=status.HTTP_404_NOT_FOUND
                )

            # 返回支付成功信息
            return Response({
                "status": 200,
                "msg": "支付成功",
                "data": {
                    "order_id": order.order_id,
                    "product": order.order_product.name,
                    "price": float(order.order_price),
                    "status": order.order_status
                }
            })
        except Exception as e:
            return Response(
                {"status": 500, "msg": f"支付结果处理异常: {str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class CheckOrderStatus(APIView):
    def get(self, request):
        try:
            order_id = request.query_params.get("order_id")
            if not order_id:
                return Response(
                    {"status": 400, "msg": "订单ID不能为空"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            order = Order.objects.filter(order_id=order_id).first()
            if not order:
                return Response(
                    {"status": 404, "msg": "订单不存在"},
                    status=status.HTTP_404_NOT_FOUND
                )

            # 修复状态检查逻辑
            if order.order_status == "已审核,未支付":
                ali = AliPaySDK()
                result = ali.query(order_id)

                trade_status = result.get("trade_status")
                if trade_status == "TRADE_SUCCESS":
                    order.order_status = "已生效"
                    order.save()
                    logger.info(f"支付宝查询接口更新订单状态: {order_id} -> 已生效")
                elif trade_status in ["TRADE_CLOSED", "TRADE_FINISHED"]:
                    return Response({
                        "status": 400,
                        "msg": "支付失败: " + trade_status,
                        "data": {
                            "order_id": order.order_id,
                            "status": "支付失败",
                            "msg": trade_status
                        }
                    })

            return Response({
                "status": 200,
                "msg": "订单状态查询成功",
                "data": {
                    "order_id": order.order_id,
                    "status": order.order_status,
                    "product": order.order_product.name
                }
            })
        except Exception as e:
            logger.error(f"订单状态查询失败: {str(e)}")
            return Response(
                {"status": 500, "msg": f"订单状态查询失败: {str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )